package com.zimmor.annotation;


import com.zimmor.util.TimeUtil;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author:zimmor
 * @Date: 2021/11/8 16:05
 * @Description
 * @version: 1.0.0
 */

public class ComponentAnnotationInit {
    public static void main(String[] args) throws Exception {
        Map springMap = getSpringMap("com.zimmor.util");
        TimeUtil timeUtil =(TimeUtil) springMap.get("timeUtil");
        timeUtil.DateToString();
        System.out.println("springMap = " + springMap);
    }

    public static Map getSpringMap(String packageName) throws Exception {
        //通过反射获取到要扫描的包
        String targetPackage = "/" + packageName.replace(".", "/");
        Set<String> classNames = new LinkedHashSet<>();
        HashMap<String, Object> springMap = new HashMap<>();
        //通过反射获取到包下所有的类，获取该文件夹下的所有文件名，加上包名，即为全限定类名。
        URL resource = Component.class.getResource(targetPackage);
        String file = resource.getFile();
        File p1 = new File(file);
        if(p1.isDirectory()) {
            File[] files = p1.listFiles();
            for (File file1 : files) {
                String name = file1.getName();
                String className = packageName + "." + name.substring(0, name.indexOf("."));
                classNames.add(className);
                System.out.println("className = " + className);
            }
        }
        System.out.println("file = " + file);
        //把获取到的类的实例添加到Spring容器中
        for (String className : classNames) {
            Object bean = Class.forName(className).getConstructor().newInstance();
            String temp = className.substring(className.lastIndexOf(".") + 1);
            String key = temp.substring(0,1).toLowerCase() + temp.substring(1);
            springMap.put(key, bean);
        }
        System.out.println("resource = " + resource);
        return springMap;
    }
}
